package edu.msg.jthr.web.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.msg.jthr.backend.exception.ServiceException;
import edu.msg.jthr.backend.model.User;
import edu.msg.jthr.backend.service.UserService;
import edu.msg.jthr.web.util.RoleAssembler;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpSession session;
	@EJB
	private UserService userService;
	private static Logger LOG = LoggerFactory.getLogger(Login.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		User user = new User();
		String role = "";
		try {
			user = userService.getUserByUserName(request.getUserPrincipal()
					.toString());
			role = RoleAssembler.getRole(user.getUserGroups());
		} catch(ServiceException e) {
			LOG.error(e.getMessage(), e);
		}
		
		session.setAttribute("role", role);
		session.setAttribute("activeUser", user);
		String pagePath = "/ShowJobs";
		request.getRequestDispatcher(pagePath).forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().write("Login Post method!");
	}

}
